package com.smarttest.base

import android.content.Context
import android.support.v4.app.Fragment
import com.smarttest.entity.NotifyEntity
import com.smarttest.ext.addDisposable
import com.smarttest.rxbus.RxBus
import dagger.android.AndroidInjector
import dagger.android.DispatchingAndroidInjector
import dagger.android.support.AndroidSupportInjection
import dagger.android.support.HasSupportFragmentInjector
import dagger.internal.Beta
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.error
import javax.inject.Inject

/**
 * 说明：通用的Fragment注入类
 * Created by code_nil on 2018/1/31.
 * 君子自强不息
 */
@Beta
abstract class BaseFragment : Fragment(), HasSupportFragmentInjector, AnkoLogger {
    @Inject
    lateinit var childFragmentInjector: DispatchingAndroidInjector<Fragment>
    lateinit var lifecycleObserver: FragmentLifecycleObserver
    override fun onAttach(context: Context) {
        AndroidSupportInjection.inject(this)
        lifecycleObserver = FragmentLifecycleObserver()
        lifecycle.addObserver(lifecycleObserver)
        super.onAttach(context)
    }

    override fun supportFragmentInjector(): AndroidInjector<Fragment>? {
        return childFragmentInjector
    }

    /**
     * 必须实现的
     */
    abstract fun getContentId(): Int


    fun registeredRxBus(action: (any: NotifyEntity) -> Unit) {
        RxBus.getDefault()
                .toObservable(NotifyEntity::class.java)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    action(it)
                }, {
                    error { "${it.message}" }
                })
                .addDisposable(lifecycleObserver.disposables)
    }

    override fun onDestroy() {
        super.onDestroy()
        //接触observer注册
        lifecycle.removeObserver(lifecycleObserver)
    }
}
